<template>
  <div class="admin-container" style="background-color: #e0e3ff">
    <!-- 主内容区 -->
    <el-main class="main-content">
      <!-- 操作区 -->
      <div class="operation-bar">
        <el-button type="primary" @click="showAddDialog">
          <el-icon><Plus /></el-icon>新增
        </el-button>
        <el-input
            v-model="searchKey"
            placeholder="搜索管理员"
            clearable
            @keyup.enter="loadData"
            class="search-input"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>

      <!-- 数据表格 -->
      <el-table :data="tableData" stripe border>
        <el-table-column prop="name" label="姓名" />
        <el-table-column prop="nickName" label="昵称" />
        <el-table-column prop="sex" label="性别" width="80" />
        <el-table-column prop="age" label="年龄" width="80" />
        <el-table-column prop="phone" label="手机号" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column label="操作" width="150">
          <template #default="{ row }">
            <el-space>
              <el-button size="small" @click="showEditDialog(row)">编辑</el-button>
              <el-button
                  size="small"
                  type="danger"
                  @click="handleDelete(row.id)"
              >
                删除
              </el-button>
            </el-space>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
          v-model:current-page="pagination.current"
          :page-size="pagination.size"
          :total="pagination.total"
          layout="total, prev, pager, next"
          @current-change="loadData"
          class="pagination"
      />

      <!-- 编辑对话框 -->
      <el-dialog
          v-model="dialogVisible"
          :title="currentAdmin.id ? '编辑管理员' : '新增管理员'"
          width="600px"
      >
        <el-form
            :model="currentAdmin"
            label-width="80px"
            :rules="formRules"
            ref="adminForm"
        >
          <el-form-item label="姓名" prop="name">
            <el-input v-model="currentAdmin.name" />
          </el-form-item>
          <el-form-item label="昵称" prop="nickName">
            <el-input v-model="currentAdmin.nickName" />
          </el-form-item>
          <el-form-item label="性别" prop="sex">
            <el-radio-group v-model="currentAdmin.sex">
              <el-radio label="男" />
              <el-radio label="女" />
            </el-radio-group>
          </el-form-item>
          <el-form-item label="年龄" prop="age">
            <el-input-number
                v-model="currentAdmin.age"
                :min="0"
                controls-position="right"
            />
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="currentAdmin.phone" />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="currentAdmin.email" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-space>
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitForm">保存</el-button>
          </el-space>
        </template>
      </el-dialog>
    </el-main>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Avatar,
  SwitchButton,
  Plus,
  Search
} from '@element-plus/icons-vue'

const router = useRouter()

// 响应式数据
const user = reactive(JSON.parse(localStorage.getItem('user')) || {})
const authority = ref([])
const permission = ref([])
const searchKey = ref('')

const tableData = ref([])
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

const dialogVisible = ref(false)
const currentAdmin = reactive({
  id: null,
  name: '',
  nickName: '',
  sex: '男',
  age: 0,
  phone: '',
  email: ''
})

const formRules = {
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确' }
  ],
  email: [
    { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
  ]
}


// 生命周期
onMounted(async () => {
  await Promise.all([loadData(), fetchPermissions()])
})

// 方法
const loadData = async (page = 1) => {
  try {
    const params = {
      pageNum: page,
      keyword: searchKey.value || undefined
    }

    const res = await axios.get('/adminInfo/page', { params })
    if (res.data.code === '0') {
      tableData.value = res.data.data.list
      pagination.current = res.data.data.pageNum
      pagination.total = res.data.data.total
    } else {
      ElMessage.error(res.data.msg)
    }
  } catch (error) {
    ElMessage.error('数据加载失败')
  }
}

const fetchPermissions = async () => {
  try {
    const [permRes, authRes] = await Promise.all([
      axios.get('/permission/1'),
      axios.get('/authority')
    ])

    if (permRes.data.code === '0') permission.value = permRes.data.data
    if (authRes.data.code === '0') authority.value = authRes.data.data
  } catch (error) {
    ElMessage.error('权限加载失败')
  }
}

const showAddDialog = () => {
  if (!checkPermission(1)) return
  Object.assign(currentAdmin, {
    id: null,
    name: '',
    nickName: '',
    sex: '男',
    age: 0,
    phone: '',
    email: ''
  })
  dialogVisible.value = true
}

const showEditDialog = (row) => {
  if (!checkPermission(3)) return
  Object.assign(currentAdmin, row)
  dialogVisible.value = true
}

const submitForm = async () => {
  try {
    await adminForm.value.validate()

    const method = currentAdmin.id ? 'put' : 'post'
    const url = currentAdmin.id ? `/adminInfo/${currentAdmin.id}` : '/adminInfo'

    const res = await axios[method](url, currentAdmin)
    if (res.data.code === '0') {
      ElMessage.success('操作成功')
      dialogVisible.value = false
      loadData(pagination.current)
    } else {
      ElMessage.error(res.data.msg)
    }
  } catch (error) {
    console.error('表单验证失败', error)
  }
}

const handleDelete = async (id) => {
  if (!checkPermission(2)) return

  try {
    await ElMessageBox.confirm('确认删除该管理员？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const res = await axios.delete(`/adminInfo/${id}`)
    if (res.data.code === '0') {
      ElMessage.success('删除成功')
      loadData()
    } else {
      ElMessage.error(res.data.msg)
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除操作失败')
    }
  }
}

const checkPermission = (requiredPerm) => {
  if (!permission.value.includes(requiredPerm)) {
    ElMessage.warning('无操作权限')
    return false
  }
  return true
}

const handleLogout = () => {
  localStorage.removeItem('user')
  router.push('/login')
}

const gotoPersonal = () => {
  router.push('/personal')
}
</script>

<style scoped>
.admin-container {
  display: flex;
  min-height: 100vh;
  background: #f0f2f5;
}

.side-menu {
  background: #fff;
  border-right: 1px solid #e8e8e8;
}

.system-title {
  height: 60px;
  line-height: 60px;
  padding: 0 20px;
  font-size: 18px;
  font-weight: 500;
  border-bottom: 1px solid #e8e8e8;
}

.nav-menu {
  border-right: none;
}

.main-content {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 20px;
  font-weight: 500;
}

.operation-bar {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
}

.search-input {
  width: 300px;
}

.pagination {
  margin-top: 20px;
  justify-content: flex-end;
}

.el-table {
  margin-top: 15px;
}
</style>